<?php


namespace app\index\controller;

use app\common\controller\CommonController;
use Exception;
use app\common\validate\UsersValidate;
use app\common\exception\ParameterFailedException;
use app\common\model\UsersModel;
use app\common\service\Redis;
use think\facade\Db;
use think\Request;
use think\response\Json;

class UsersController extends CommonController
{
    /**
     * @return Json
     * @throws Exception
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/7/7
     * @Time: 15:38
     */
    public function register(Request $request): ?\think\response\Json
    {
        $params = self::getParam([
            'mobile_number',
            'password',
        ]);
        (new UsersValidate())->goCheck(__FUNCTION__, $params);

        $userModel = UsersModel::where('mobile_number', $params['mobile_number'])->field('*')->find();
        if ($userModel) {
            throw new ParameterFailedException(['msg' => '手机号已存在']);
        }
        Db::startTrans();
        try {
            $accessToken              = getToken();
            $cryptRes                 = cryptPassword($params['password']);
            $userModel                = new UsersModel();
            $userModel->mobile_number = $params['mobile_number'];
            $userModel->password      = $cryptRes['password'];
            $userModel->salt          = $cryptRes['salt'];
            $userModel->login_ip      = $request->ip();
            $userModel->login_time    = NOW_TIME;
            $userModel->group_id      = 1;
            $userModel->save();

            Redis::setAccessToken($accessToken, $userModel->id,'default');
            Db::commit();
            return retJson('注册成功', ['access_token' => $accessToken]);
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }


    /**
     * 获取用户列表-分页获取
     * @param  string  $page
     * @param  string  $limit
     * @return Json
     * @throws \think\db\exception\DbException
     *
     * @Author: Li Guo Xin <guoxinlee129@gmail.com>
     * @Date: 2020/7/8
     * @Time: 9:35
     */
    public function getUserList($page = '1', $limit = '10'): Json
    {
        $userListData = (new UsersModel())->paginate([
            'page'      => $page,
            'list_rows' => $limit,
        ]);

        return retJson('获取成功', $userListData);
    }
}